import { evaluateState, FAction, robotState } from '@/plugins/constants'
import { requestDestroyRobot } from '@/service'
import { useChannelStore } from '@/store/channel'
import { useChatStore } from '@/store/chat'
import { useSessionStore } from '@/store/session'
import { useWebWorker } from '@vueuse/core'
import { remove } from 'lodash'
import { v7 as uuidv7 } from 'uuid'
import { watch } from 'vue'
const useWorker = (file) => {
  const { data, post, terminate, worker } = useWebWorker(file)
  const start = () => {
    // console.log('start------------worker')
    post({ type: 'start' })
  }
  const stop = () => {
    // console.log('stop------------worker')
    post({ type: 'stop' })
  }
  const close = () => {
    console.log('close------------worker')
    terminate()
  }
  const destroy = () => {
    const session = useSessionStore()
    const chat = useChatStore()
    const channel = useChannelStore()
    // 机器人销毁
    requestDestroyRobot({
      meetingId: session.meetingId,
    }).then(() => {
      console.log(
        '销毁机器人',
        channel.systemInfo.robotInvalid,
        session.robotEvaluate,
      )
      session.updateActionState(FAction.DESTROY_ROBOT)
      session.updateRobotState(robotState.DESTROY) // 销毁机器人
      remove(chat.messageList, (item: any) => item.channelType === 'robot')
      // 渠道结束语
      chat.updateMessages({
        content: channel.systemInfo.channelEnding,
        role: 'system',
        channelType: 'robot',
        type: 'text',
        id: uuidv7(),
      })
      // 判断是否开启无效会话推送评价
      if (
        channel.systemInfo.robotInvalid &&
        session.robotEvaluate === evaluateState.uncompleted
      ) {
        // 判断当前窗口是否已经有评价
        const evalFlag = chat.messageList.some(
          (item: any) => item.type === 'evaluate' && item.target === 'robot',
        )
        if (!evalFlag) {
          // 推送评价
          // evalType: 1-机器人对话后定时销毁推送满意度 2-坐席邀评 3-访客主动评价 4-人工结束推送
          chat.updateMessages({
            role: 'system',
            type: 'evaluate',
            target: 'robot',
            evalType: 1,
            id: uuidv7(),
          })
        }
      }
    })
  }
  // 监听worker数据变化
  watch(
    () => data.value,
    (data) => {
      if (data.value === 'kill') {
        destroy()
      }
    },
  )
  return {
    data,
    post,
    terminate,
    worker,
    start,
    stop,
    close,
  }
}
export default useWorker
